/*
 * THE SOURCE CODES OF THE SOFTWARE ARE VALUABLE ASSETS OF FIDUS TECHNOLOGIES LTD.
 * YOU AGREE TO KEEP ALL SOURCE CODES OF THE SOFTWARE IN CONFIDENCE. YOU MAY NOT TRANSFER
 * OR ASSIGN THE SOFTWARE OR YOUR RIGHTS UNDER THIS AGREEMENT.
 * LIMITED WARRANTY
 * THE SOFTWARE AND ACCOMPANYING WRITTEN MATERIALS (INCLUDING INSTRUCTIONS FOR USE) ARE PROVIDED "AS IS"
 * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. YOU ASSUME THE ENTIRE
 * RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE.
 * FIDUS TECHNOLOGIES DOES NOT WARRANT THAT THE SOFTWARE WILL MEET ALL YOUR REQUIREMENTS, THAT OPERATIONS
 * OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT ALL SOFTWARE ERRORS WILL BE CORRECTED.
 * FIDUS TECHNOLOGIES-SOFTWARE SOLUTIONS IS NOT RESPONSIBLE FOR PROBLEMS CAUSED BY CHANGES IN THE
 * OPERATING CHARACTERISTICS OF COMPUTER HARDWARE OR COMPUTER OPERATING SYSTEMS WHICH ARE MADE AFTER
 * WHICH ARE MADE AFTER THE RELEASE OF THE SOFTWARE NOR FOR PROBLEMS IN THE INTERACTION OF THE SOFTWARE
 * WITH NON-FIDUS TECHNOLOGIES APPLICATION.WILL HAVE NO RESPONSIBILITY TO REPLACE OR REFUND THE LICENSE FEES
 * FOR MEDIA DAMAGED BY ACCIDENT, ABUSE OR MISAPPLICATION. THIS SOFTWARE IS INTENDED FOR COMMERCIAL,
 * INSTITUTIONAL, AND INDUSTRIAL USERS. THE ABOVE WARRANTIES ARE EXCLUSIVE AND IN LIEU OF ALL OTHER WARRANTIES,
 * WHETHER EXPRESSED OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NON-INFRINGEMENT. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY FIDUS TECHNOLOGIES,
 * ITS EMPLOYEES, DISTRIBUTORS, DEALERS OR AGENTS SHALL INCREASE THE SCOPE OF THE ABOVE WARRANTIES OR
 * CREATE ANY NEW WARRANTIES. NEITHER FIDUS TECHNOLOGIES NOR ANYONE ELSE WHO HAS BEEN INVOLVED IN THE
 * CREATION, PRODUCTION OR DELIVERY OF THE SOFTWARE SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES (INCLUDING DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS LOSSES, BUSINESS
 * INTERRUPTION, LOSS OF DATA, AND THE LIKE) ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE,
 * OR ANY OTHER CLAIM BY ANY PARTY EVEN IF FIDUS TECHNOLOGIES HAS BEEN ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGES. IN THE EVENT FIDUS TECHNOLOGIES IS LIABLE FOR ANY DAMAGES, FIDUS TECHNOLOGIES' LIABILITY
 * FOR DAMAGES SHALL BE LIMITED TO THE AMOUNT PAID FOR THE SOFTWARE UNDER THE TERMS AND CONDITIONS OF THIS
 * AGREEMENT.
 * http://www.fidustechnologies.com
 * Copyright(C) 2010 FIDUS TECHNOLOGIES-Software Solutions(R)
 * All rights reserved.
 */

/*
 * SearchProductView.java
 *
 * Created on 2 Sep, 2010, 4:05:51 PM
 */

package com.fidus.inventory.UI.products;

import com.fidus.inventory.UI.docking.MainScreen;
import com.fidus.inventory.beans.products.ProductDetails;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.application.Action;

/**
 *
 * @author Mahesh Kedari<mahesh.kedari@fidustechnologies.com>
 */
public class SearchProductView extends javax.swing.JPanel {

    /** Creates new form SearchProductView */
    public SearchProductView() {
        initComponents();
        /*
         * Add Listener for selection on product Table and change value of
         * productSelected flag accordingly
         */
        productsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent lse) {
                propertyChangeSupport.firePropertyChange(PROP_PRODUCTSELECTED, isProductSelected(),!isProductSelected());
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        inventorymanagement_dbPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("inventorymanagement_dbPU").createEntityManager();
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getResourceMap(SearchProductView.class);
        productdetailsQuery = java.beans.Beans.isDesignTime() ? null : inventorymanagement_dbPUEntityManager.createQuery(resourceMap.getString("productdetailsQuery.query")); // NOI18N
        productdetailsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(productdetailsQuery.getResultList());
        productPopupMenu = new javax.swing.JPopupMenu();
        refreshMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        viewMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        newMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        orderMenuItem = new javax.swing.JMenuItem();
        quotationMenuItem = new javax.swing.JMenuItem();
        salesMenu = new javax.swing.JMenu();
        salesReportMenuItem = new javax.swing.JMenuItem();
        lastSaleMenuItem = new javax.swing.JMenuItem();
        searchPanel = new org.jdesktop.swingx.JXTitledPanel();
        searchForLabel = new javax.swing.JLabel();
        searchForTextField = new javax.swing.JTextField();
        searchTypeLabel = new javax.swing.JLabel();
        searchTypeComboBox = new javax.swing.JComboBox();
        matchTypeLabel = new javax.swing.JLabel();
        matchTypeComboBox = new javax.swing.JComboBox();
        searchButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        productsTable = new org.jdesktop.swingx.JXTable();

        productPopupMenu.setName("productPopupMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getActionMap(SearchProductView.class, this);
        refreshMenuItem.setAction(actionMap.get("refresh")); // NOI18N
        refreshMenuItem.setName("refreshMenuItem"); // NOI18N
        productPopupMenu.add(refreshMenuItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        productPopupMenu.add(jSeparator1);

        viewMenuItem.setAction(actionMap.get("viewDetails")); // NOI18N
        viewMenuItem.setName("viewMenuItem"); // NOI18N
        productPopupMenu.add(viewMenuItem);

        deleteMenuItem.setAction(actionMap.get("deleteProduct")); // NOI18N
        deleteMenuItem.setName("deleteMenuItem"); // NOI18N
        productPopupMenu.add(deleteMenuItem);

        newMenuItem.setAction(actionMap.get("newProduct")); // NOI18N
        newMenuItem.setText(resourceMap.getString("newMenuItem.text")); // NOI18N
        newMenuItem.setName("newMenuItem"); // NOI18N
        productPopupMenu.add(newMenuItem);

        jSeparator2.setName("jSeparator2"); // NOI18N
        productPopupMenu.add(jSeparator2);

        orderMenuItem.setAction(actionMap.get("openSalesOrder")); // NOI18N
        orderMenuItem.setName("orderMenuItem"); // NOI18N
        productPopupMenu.add(orderMenuItem);

        quotationMenuItem.setAction(actionMap.get("openQuotation")); // NOI18N
        quotationMenuItem.setText(resourceMap.getString("quotationMenuItem.text")); // NOI18N
        quotationMenuItem.setName("quotationMenuItem"); // NOI18N
        productPopupMenu.add(quotationMenuItem);

        salesMenu.setText(resourceMap.getString("salesMenu.text")); // NOI18N
        salesMenu.setName("salesMenu"); // NOI18N

        salesReportMenuItem.setAction(actionMap.get("salesReport")); // NOI18N
        salesReportMenuItem.setText(resourceMap.getString("salesReportMenuItem.text")); // NOI18N
        salesReportMenuItem.setName("salesReportMenuItem"); // NOI18N
        salesMenu.add(salesReportMenuItem);

        lastSaleMenuItem.setAction(actionMap.get("lastSale")); // NOI18N
        lastSaleMenuItem.setText(resourceMap.getString("lastSaleMenuItem.text")); // NOI18N
        lastSaleMenuItem.setName("lastSaleMenuItem"); // NOI18N
        salesMenu.add(lastSaleMenuItem);

        productPopupMenu.add(salesMenu);

        setName("Form"); // NOI18N

        searchPanel.setTitle(resourceMap.getString("searchPanel.title")); // NOI18N
        searchPanel.setName("searchPanel"); // NOI18N

        searchForLabel.setText(resourceMap.getString("searchForLabel.text")); // NOI18N
        searchForLabel.setName("searchForLabel"); // NOI18N

        searchForTextField.setText(resourceMap.getString("searchForTextField.text")); // NOI18N
        searchForTextField.setName("searchForTextField"); // NOI18N

        searchTypeLabel.setText(resourceMap.getString("searchTypeLabel.text")); // NOI18N
        searchTypeLabel.setName("searchTypeLabel"); // NOI18N

        searchTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Code", "Name", "Description" }));
        searchTypeComboBox.setName("searchTypeComboBox"); // NOI18N

        matchTypeLabel.setText(resourceMap.getString("matchTypeLabel.text")); // NOI18N
        matchTypeLabel.setName("matchTypeLabel"); // NOI18N

        matchTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contains", "Exact" }));
        matchTypeComboBox.setName("matchTypeComboBox"); // NOI18N

        searchButton.setAction(actionMap.get("searchProduct")); // NOI18N
        searchButton.setText(resourceMap.getString("searchButton.text")); // NOI18N
        searchButton.setName("searchButton"); // NOI18N

        clearButton.setAction(actionMap.get("clearForm")); // NOI18N
        clearButton.setText(resourceMap.getString("clearButton.text")); // NOI18N
        clearButton.setName("clearButton"); // NOI18N

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel.getContentContainer());
        searchPanel.getContentContainer().setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(searchForLabel)
                    .addComponent(searchTypeLabel)
                    .addComponent(matchTypeLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(matchTypeComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchTypeComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchForTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(searchButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                .addComponent(clearButton)
                .addGap(21, 21, 21))
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchForLabel)
                    .addComponent(searchForTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchTypeLabel)
                    .addComponent(searchTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(matchTypeLabel)
                    .addComponent(matchTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(searchButton)
                    .addComponent(clearButton))
                .addContainerGap())
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        productsTable.setName("productsTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, productdetailsList, productsTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${productCode}"));
        columnBinding.setColumnName("Product Code");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${productName}"));
        columnBinding.setColumnName("Product Name");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        productsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                productsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(productsTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(searchPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void productsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_productsTableMouseClicked
        if(evt.getButton()== MouseEvent.BUTTON3){
            productPopupMenu.show(productsTable, evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_productsTableMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearButton;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.persistence.EntityManager inventorymanagement_dbPUEntityManager;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JMenuItem lastSaleMenuItem;
    private javax.swing.JComboBox matchTypeComboBox;
    private javax.swing.JLabel matchTypeLabel;
    private javax.swing.JMenuItem newMenuItem;
    private javax.swing.JMenuItem orderMenuItem;
    private javax.swing.JPopupMenu productPopupMenu;
    private java.util.List<com.fidus.inventory.beans.products.ProductDetails> productdetailsList;
    private javax.persistence.Query productdetailsQuery;
    private org.jdesktop.swingx.JXTable productsTable;
    private javax.swing.JMenuItem quotationMenuItem;
    private javax.swing.JMenuItem refreshMenuItem;
    private javax.swing.JMenu salesMenu;
    private javax.swing.JMenuItem salesReportMenuItem;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel searchForLabel;
    private javax.swing.JTextField searchForTextField;
    private org.jdesktop.swingx.JXTitledPanel searchPanel;
    private javax.swing.JComboBox searchTypeComboBox;
    private javax.swing.JLabel searchTypeLabel;
    private javax.swing.JMenuItem viewMenuItem;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Search Panel buttons Action Handling">
    /**
     * Search the product as per the criteria given is search panel and modify the
     * result list accordingly.
     */
    @Action
    public void searchProduct(){
        //TODO Search product list according to selection criteria given.
    }

    /**
     * Clear the search Panel and reset result list. 
     */
    @Action
    public void clearForm(){
        //TODO clear form and selection
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Popup menu action handling">
    /**
     * This action will refresh the product list
     */
    @Action
    public void refresh(){
        //TODO Refresh product list
    }

    protected boolean productSelected;
    public static final String PROP_PRODUCTSELECTED = "productSelected";

    /**
     * Get the value of productSelected
     *
     * @return the value of productSelected
     */
    public boolean isProductSelected() {
        return productsTable.getSelectedRow()!=-1;
    }

    /**
     * Set the value of productSelected
     *
     * @param productSelected new value of productSelected
     */
    public void setProductSelected(boolean productSelected) {
        boolean oldProductSelected = this.productSelected;
        this.productSelected = productSelected;
        propertyChangeSupport.firePropertyChange(PROP_PRODUCTSELECTED, oldProductSelected, productSelected);
    }

    /**
     * This action will view details of selected product
     */
        @Action(enabledProperty="productSelected")
    public void viewDetails(){
            ProductDetails product = productdetailsList.get(productsTable.convertRowIndexToModel(productsTable.getSelectedRow()));
            Component component = MainScreen.selfObject.getDockedComponent("Product", product.getProductCode());
            if(component instanceof ProductDetailsView){
                ProductDetailsView productDetailsView = (ProductDetailsView)component;
                productDetailsView.setProduct(product);
                productDetailsView.setValidProduct(true);

            }
    }

    /**
     * This action will delete selected product
     */
        @Action(enabledProperty="productSelected")
    public void deleteProduct(){
        //TODO Delete selected Product
    }

    /**
     * This action will navigate user to create new product screen
     */
    @Action
    public void newProduct(){
        //TODO New Product in product List
    }

    /**
     * This action will open new invoice with selected product inserted in
     * table
     */
        @Action(enabledProperty="productSelected")
    public void openSalesOrder(){
        //TODO Open new invoice with selected product
    }

    /**
     * This action will open new Quotation with selected product inserted in
     * table
     */
        @Action(enabledProperty="productSelected")
    public void openQuotation(){
        //TODO Open new Qotation with selected product
    }

    /**
     * This action will display graphical report of sale of selected Product
     */
        @Action(enabledProperty="productSelected")
    public void salesReport(){
        //TODO view sales report of selected product
    }
    /**
     * This action will display sales report of selected product
     */
        @Action(enabledProperty="productSelected")
    public void lastSale(){
        //TODO  View last sale details of selected product
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Property Change Support">
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }
    //</editor-fold>

}
